package com.edu.robot.core.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.edu.chat.facade.facade.MessageFacade;
import com.edu.chat.facade.facade.SessionFacade;
import com.edu.chat.facade.model.dto.HistoryMsgDTO;
import com.edu.chat.facade.model.enums.MsgTypeEnum;
import com.edu.robot.common.constants.IMConstant;
import com.edu.robot.common.service.RedisUtil;
import com.edu.robot.core.enums.IntentEnum;
import com.edu.robot.core.enums.NotifyMsgEnum;
import com.edu.robot.core.model.APICallback;
import com.edu.robot.core.model.SessionContext;
import com.edu.robot.model.enums.ResultCodeEnum;
import com.edu.robot.model.error.BizException;
import com.edu.robot.modules.robot.dto.ModelConfigDTO;
import com.edu.robot.modules.robot.dto.PromptDTO;
import com.edu.robot.modules.robot.dto.RobotConfigDTO;
import com.edu.robot.modules.robot.service.CrModelConfigService;
import com.edu.robot.modules.robot.service.CrPromptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-23 18:05
 **/

@Component("chatModelProcess")
@Slf4j
public class ChatModelProcess extends AbstractModelInvoke {

	@Autowired
	private CrModelConfigService crModelConfigService;

	@Autowired
	private CrPromptService crPromptService;

	@Autowired
	private RedisUtil redisUtil;

	@DubboReference(interfaceClass = MessageFacade.class,check = false)
	private MessageFacade messageFacade;

	@Override
	public void buildModel(SessionContext sessionContext) {

		//是否命中缓存
		final String sessionKey = IMConstant.MODEL_CONFIG_REDIS_KEY+sessionContext.getRobot().getRobotConfig().getModelConfigId();

		ModelConfigDTO modelConfigDTO = redisUtil.get(sessionKey, ModelConfigDTO.class);

		if(modelConfigDTO == null){
			//从数据库中获取模型信息
			modelConfigDTO = crModelConfigService.queryConfigById(Long.valueOf(sessionContext.getRobot()
					.getRobotConfig()
					.getModelConfigId()));
			if(modelConfigDTO == null){
				throw new BizException(ResultCodeEnum.DATABASE_ERROR,"模型配置信息为空！");
			}
			//设置模型信息到redis中
			redisUtil.set(sessionKey,modelConfigDTO,60*5);
		}

		sessionContext.setModelConfigDTO(modelConfigDTO);
	}

	@Override
	public void buildPrompt(SessionContext sessionContext) {

		//获取模板ID
		RobotConfigDTO robotConfig = sessionContext.getRobot().getRobotConfig();

		String promptId = robotConfig.getPromptId();

		String sysPrompt= IntentEnum.INTENT_CHAT.getSysPrompt();

		String userPrompt="";
		//使用默认模板
		if(StringUtils.isNotBlank(promptId)){

			//是否命中缓存
			final String sessionKey = IMConstant.ROBOT_PROMPT_REDIS_KEY+promptId;

			PromptDTO promptDTO = redisUtil.get(sessionKey, PromptDTO.class);

			if(promptDTO == null){
				//从数据库中获取模板信息
				promptDTO = crPromptService.getPromptById(Long.valueOf(promptId));
				if(promptDTO == null){
					throw new BizException(ResultCodeEnum.DATABASE_ERROR,"模板信息不存在");
				}
				//设置模板信息到redis中
				redisUtil.set(sessionKey,promptDTO,60*5);
			}
			userPrompt= promptDTO.getContent();
		}

		//获取历史消息
		List<HistoryMsgDTO> historyMsgDTOS = messageFacade.queryMsgList(sessionContext.getSessionId(), sessionContext.getTenantId());
		String historyMsg = buildHistoryMsg(historyMsgDTOS);

		historyMsg=StringUtils.isBlank(historyMsg) ? "null" : historyMsg;

		String format = String.format(sysPrompt, historyMsg, sessionContext.getAgentAnswer(), userPrompt);

		log.info("ChatModelProcess buildPrompt res:{}",format);
		sessionContext.setPrompt(format);

	}

	@Override
	public String invokeModel(SessionContext sessionContext) {

		String finalMsg = modelManger.modelInvokeStream(sessionContext);

		log.info("ChatModelProcess invokeModel res:{}",finalMsg);
		return finalMsg;
	}

	//直接走闲聊
	public String invokeFallback(SessionContext sessionContext) {
		log.info("直接走闲聊:{}",sessionContext);

		//构建模型参数
		buildModel(sessionContext);

		//替换提示词模板
		buildPrompt(sessionContext);

		return invokeModel(sessionContext);

	}

	//构建历史消息模板
	private String buildHistoryMsg(List<HistoryMsgDTO> historyMsgDTOS){

		if(CollectionUtil.isEmpty(historyMsgDTOS)){
			return "";
		}
		/**
		* 用户：%s
		 * 机器人：%s
		*/
		StringBuilder msgTemplate = new StringBuilder();
		 historyMsgDTOS.forEach(historyMsgDTO -> {

			MsgTypeEnum type = historyMsgDTO.getType();
			if(Objects.equals(type,MsgTypeEnum.USER)){
				msgTemplate.append("用户:").append(historyMsgDTO.getContent()).append("\n");
			}else {
				msgTemplate.append("机器人:").append(historyMsgDTO.getContent()).append("\n");
			}
		});

		return msgTemplate.toString();


	}

}
